<template>
  <div>
    <el-main>
      <div class="box">
        <div class="top">
          <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="float: left" size="medium">
            <el-form-item label="监测时间">
              <el-date-picker v-model="queryForm.year" type="year" format="yyyy" value-format="yyyy" placeholder="选择年月">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="样地编号：">
              <el-input v-model="queryForm.yangdibh" placeholder="样地编号" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button @click="showAdvancedSearch">高级搜索</el-button>
            </el-form-item>
          </el-form>
          <div style="
              float: right;
              margin-right: 60px;
              display: flex;
              align-items: center;
            ">
            <el-button type="primary" size="medium" @click="showForm">添加</el-button>
            <!-- <el-button type="danger" :disabled="selection.length === 0" style="margin-right: 10px"
              @click="batchDelete">批量删除</el-button> -->
            <el-button type="success" @click="openDialog">Excel批量导入</el-button>
            <el-dialog :visible.sync="dialogVisible" title="Excel导入" class="excel-dialo"
              :before-close="handleDialogClose" top="5vh">
              <!-- 选中文件的input -->
              <div>
                <div style="margin-bottom: 10px;">
                  <el-button type="primary" @click="openExcel" size="medium">从Excel导入</el-button>
                  <input ref="exceluploadinput" type="file" accept=".xlsx, .xls" style="display: none;"
                    @change="handleFileUpload" />
                </div>
                <el-tabs type="border-card">
                  <el-tab-pane label="样地信息">
                    <el-table :data="ydpaginatedData" style="width: 100%" height="400px" size="medium" border>
                      <el-table-column prop="originalPlotId" label="样地编号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="ecosystemTypeVegetation" label="生态系统类型/植被型或亚型" width="210"
                        show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="vegetationGroup" label="群系或群系组" width="115" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="communityName" label="群丛名称" width="150" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="location" label="调查地点" width="300" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="longitude" label="经度（°）" width="90" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="latitude" label="纬度（°）" width="90" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="elevation" label="海拔（m）" width="90" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="topography" label="地形地貌" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="slopeDirection" label="坡向" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="slopePosition" label="坡位" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="slopeDegree" label="坡度" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="disturbanceLevel" label="干扰程度" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="disturbanceType" label="干扰类型" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="artificialPlanting" label="人工种植" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="treeLayer" label="乔木层" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="shrubLayer" label="灌木层" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="herbLayer" label="草本层" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="mossLichenLayer" label="苔藓地衣层" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="surfaceFeatures" label="地表特征" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="soilType" label="土壤类型" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="soilTexture" label="土壤质地" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="soilMeasurement" label="土壤测定" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="investigator" label="调查/监管人" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="recorder" label="记录人" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="surveyDate" label="调查日期" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="projectLeader" label="课题负责人" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="ecosystemCategory" label="生态系统类型" width="115" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="otherNotes" label="其它记录" show-overflow-tooltip>
                      </el-table-column>
                    </el-table>
                    <el-pagination @size-change="handleSizeChange($event, 'yd')"
                      @current-change="handleCurrentChange2($event, 'yd')" :current-page="pagination.ydcurrentPage"
                      :page-sizes="[10, 20, 50, 100]" :page-size="pagination.ydpageSize"
                      layout="total, sizes, prev, pager, next" :total="pagination.ydtotal">
                    </el-pagination>
                  </el-tab-pane>
                  <el-tab-pane label="草本样方">
                    <el-table :data="cbpaginatedData" style="width: 100%" height="400px" size="medium" border>
                      <el-table-column prop="originalPlotId" label="样地编号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="herbQuadratId" label="草本样方编号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="quadratRecorder" label="样方记录人" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="quadratAreaM2" label="样方面积" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="totalCoveragePct" label="总盖度%" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="layerHeightCm" label="草层高度cm" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="speciesField" label="物种名（野外记录）" width="180" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="chineseName" label="中文名（校对）" width="140" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="latinNameField" label="拉丁名" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="vegetativeBranchHeightCm" label="营养枝高cm" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="partialCoveragePct" label="分盖度%" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="clusterCount" label="株丛数" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="biomassFreshGM2" label="生物量鲜重 g/m2" width="140" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="biomassDryGM2" label="生物量干重 g/m2" width="140" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="abundanceLevel" label="多度级" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="photoId" label="照片编号" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="surveyYear" label="调查年" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="ecosystemType" label="生态系统类型" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="projectLeader" label="课题负责人" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="notes" label="注明" width="100" show-overflow-tooltip>
                      </el-table-column>
                    </el-table>
                    <el-pagination @size-change="handleSizeChange($event, 'cb')"
                      @current-change="handleCurrentChange2($event, 'cb')" :current-page="pagination.cbcurrentPage"
                      :page-sizes="[10, 20, 50, 100]" :page-size="pagination.cbpageSize"
                      layout="total, sizes, prev, pager, next" :total="pagination.cbtotal">
                    </el-pagination>
                  </el-tab-pane>
                  <el-tab-pane label="灌木样方">
                    <el-table :data="gmpaginatedData" style="width: 100%" height="400px" size="medium" border>
                      <el-table-column prop="originalPlotId" label="样地编号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="shrubQuadratId" label="灌木样方号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="quadratRecorder" label="样方记录人" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="quadratArea" label="样方面积" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="totalCoveragePct" label="灌木总盖度%" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="layerHeightCm" label="灌木层高度cm" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="speciesField" label="物种名（野外记录）" width="180" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="chineseName" label="中文名（校对）" width="140" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="latinName" label="拉丁名" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="plantId" label="植株编号" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="averageHeightCm" label="平均高度（cm）" width="140" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="stemCount" label="茎杆数" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="averageStemBaseDiameterCm" label="茎杆平均基径(cm)" width="160"
                        show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="crownLongAxisCm" label="冠幅长轴(cm)" width="130" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="crownShortAxisCm" label="冠幅短轴(cm)" width="130" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="biomassGM2" label="生物量 g/m2" width="115" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="biomassMethod" label="生物量取样测定方法描述" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="photoId" label="照片编号" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="clusterCount" label="株丛数" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="surveyYear" label="调查年" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="ecosystemType" label="生态系统类型" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="projectLeader" label="课题负责人" width="100" show-overflow-tooltip>
                      </el-table-column>
                    </el-table>
                    <el-pagination @size-change="handleSizeChange($event, 'gm')"
                      @current-change="handleCurrentChange2($event, 'gm')" :current-page="pagination.gmcurrentPage"
                      :page-sizes="[10, 20, 50, 100]" :page-size="pagination.gmpageSize"
                      layout="total, sizes, prev, pager, next" :total="pagination.gmtotal">
                    </el-pagination>
                  </el-tab-pane>
                  <el-tab-pane label="乔木样方">
                    <el-table :data="qmpaginatedData" style="width: 100%" height="400px" size="medium" border>
                      <el-table-column prop="originalPlotId" label="样地编号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="treeQuadratId" label="乔木样方号" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="quadratRecorder" label="样方记录人" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="quadratAreaM" label="样方面积" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="totalCoveragePct" label="乔木总盖度%" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="layerHeightCm" label="乔木层高度cm" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="measurementStandard" label="每木检尺测起测标准" width="150" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="speciesField" label="物种名（野外记录）" width="180" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="chineseName" label="中文名（校对）" width="140" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="latinName" label="拉丁名" width="100" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="plantId" label="植株编号" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="heightM" label="高度 m" width="70" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="branchHeightM" label="枝下高 m" width="80" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="dbhCm" label="胸径 cm (1.3m 处）" width="160" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="circumferenceCm" label="胸周长 cm (1.3m 处）" width="170" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="crownLongAxisCm" label="冠幅长轴(cm)" width="130" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="crownShortAxisCm" label="冠幅短轴(cm)" width="130" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="biomassGM2" label="生物量 g/m2" width="115" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="biomassMethod" label="生物量取样测定方法描述" width="200" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="photoId" label="照片编号" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="surveyYear" label="调查年" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="ecosystemType" label="生态系统类型" width="120" show-overflow-tooltip>
                      </el-table-column>
                      <el-table-column prop="projectLeader" label="课题负责人" width="100" show-overflow-tooltip>
                      </el-table-column>
                    </el-table>
                    <el-pagination @size-change="handleSizeChange($event, 'qm')"
                      @current-change="handleCurrentChange2($event, 'qm')" :current-page="pagination.qmcurrentPage"
                      :page-sizes="[10, 20, 50, 100]" :page-size="pagination.qmpageSize"
                      layout="total, sizes, prev, pager, next" :total="pagination.qmtotal">
                    </el-pagination>
                  </el-tab-pane>
                </el-tabs>
                <!-- <div class="batch-btn-row">
                  <label class="file-upload batch-btn">
                    <input ref="fileInput" type="file" @change="handleFileUpload" />
                    选择文件
                  </label>
                  <el-button type="success" size="small" icon="el-icon-download" class="batch-btn"
                    @click="downloadTemplate">
                    下载模板
                  </el-button>
                  <el-button type="primary" size="small" class="batch-btn" :disabled="isButtonDisabled ||
                    formDataExcel.length === 0 ||
                    errorMessages.length > 0
                    " @click="insertAllDataFromExcel">
                    {{ buttonText }}
                  </el-button>
                </div> -->

                <!-- 错误信息提示 -->
              </div>
              <template slot="footer">
                <el-link type="primary" :underline="false" :href="excelurl">点击下载示例数据</el-link>
                <span>
                  <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
                  <el-button type="primary" @click="handsubmit" size="medium">导 入</el-button>
                </span>
              </template>
              <!-- <div v-if="errorMessages.length > 0" class="error-messages" style="
                  text-align: center;
                  color: #f56c6c;
                  background-color: #fef0f0;
                  padding: 10px;
                  border-radius: 4px;
                  margin-top: 10px;
                ">
                <p v-for="(message, index) in errorMessages" :key="index" style="margin: 5px 0">
                  {{ message }}
                </p>
              </div> -->
            </el-dialog>
          </div>
        </div>
        <div class="center">
          <el-table :data="paginatedData" border style="width: 100%" size="medium" :max-height="tableheight"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" show-overflow-tooltip />
            <el-table-column prop="id" label="ID" width="60px" show-overflow-tooltip />
            <el-table-column prop="yangdibh" label="样地编号" show-overflow-tooltip />

            <el-table-column prop="shengtaixitonglx" label="生态系统类型" width="120" show-overflow-tooltip />
            <el-table-column prop="xzqhmc" label="行政区划" show-overflow-tooltip />
            <!-- <el-table-column
              prop="qixian"
              label="旗县"
              width="100"
              show-overflow-tooltip
            /> -->
            <el-table-column prop="lon" label="经度" width="95" show-overflow-tooltip />
            <el-table-column prop="lat" label="纬度" width="95" show-overflow-tooltip />
            <el-table-column prop="hb" label="海拔" width="80" show-overflow-tooltip />
            <el-table-column prop="jianceshijian" label="监测时间" width="120">
              <template slot-scope="scope">
                {{ format(scope.row.jianceshijian) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag type="success" size="small">已录入</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="action" label="操作" width="170" align="center">
              <template slot-scope="scope">
                <!-- 操作按钮 -->
                <el-button type="primary" size="mini" @click="handleButtonClick(scope.row)">
                  修改
                </el-button>
                <el-button type="danger" size="mini" @click="deleteItem(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="bottom">
        <el-pagination :current-page="currentPage" background layout="total, prev, pager, next, jumper"
          :total="totalItems" :page-size="pageSize" @current-change="handleCurrentChange" />
      </div>
    </el-main>

    <!-- 高级搜索对话框 -->
    <el-dialog title="高级搜索" :visible.sync="advancedSearchVisible" width="500" :before-close="handleAdvancedSearchClose">
      <el-form :model="advancedSearchForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="监测时间">
              <el-date-picker v-model="advancedSearchForm.year" type="year" format="yyyy" value-format="yyyy"
                placeholder="选择年" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区划：">
              <el-input v-model="advancedSearchForm.xzqhmc" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样地编号：">
              <el-input v-model="advancedSearchForm.yangdibh" placeholder="请输入样地编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度：">
              <el-input v-model="advancedSearchForm.lon" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度：">
              <el-input v-model="advancedSearchForm.lat" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="海拔：">
              <el-input v-model="advancedSearchForm.hb" placeholder="请输入海拔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生态系统类型：">
              <el-input v-model="advancedSearchForm.shengtaixitonglx" placeholder="生态系统类型" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="advancedSearchVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdvancedSearch">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { MessageBox, Message } from "element-ui";
import * as XLSX from "xlsx";
import { readExcel } from '@/utils/readNdExcel.js'
export default {
  name: "APP",
  data() {
    return {
      tableheight: 300,
      value2: "",
      filteredData: [], // 根据查询条件过滤后的数据
      queryForm: {
        yangdibh: '',
        year: '',
      },
      tableData: [], // 样地数据
      paginatedData: [], // 当前页的数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数据量
      totalItems: 0, // 总项目数
      // showFormFlag: false, // 控制表单显示与隐藏的标志
      formData: "", // 用于绑定表单输入数据的变量
      selectedCategory: "全部", // 存储选中的样地种类
      categories: [
        // 样地种类选项
        { label: "草普", value: "草普" },
        { label: "地面数据", value: "地面数据" },
        { label: "一站多点", value: "一站多点" },
        { label: "国家站", value: "国家站" },
        { label: "全部", value: "全部" },
      ],
      addFormData: [
        {
          category: null,
          cbceng: null,
          diaocha: null,
          dlw: null,
          dlwdm: null,
          dxdm: null,
          fs: null,
          fsdm: null,
          fusha: null,
          fushadm: null,
          geom: null,
          gmceng: null,
          haiba: null,
          id: null,
          jiancequ: null,
          jilu: null,
          lat: null,
          lk: null,
          lkdm: null,
          located: null,
          lon: null,
          ls: null,
          lsdm: null,
          lycd: null,
          lycddm: null,
          lyfs: null,
          lyfsdm: null,
          miaoshu: null,
          pd: null,
          pw: null,
          pwdm: null,
          px: null,
          pxdm: null,
          qmceng: null,
          qunluo: null,
          qunxi: null,
          rengongzhongzhi: null,
          riqi: null,
          sampleid: null,
          samplename: null,
          ss: null,
          ssdm: null,
          trceding: null,
          trlx: null,
          trlxdm: null,
          trzhidi: null,
          txdyceng: null,
          xzqhcode: null,
          xzqhname: null,
          yjd: null,
          yjddm: null,
          zbjieguo: null,
          zblx: null,
          zblxdm: null,
          zllx: null,
          zpbh: null,
        },
      ],
      // 存储Excel文件数据
      excelData: null,
      formDataExcel: [],
      duplicateSampleIds: new Set(),
      isButtonDisabled: false, // 初始化按钮可点击状态
      buttonText: "录入全部数据", // 初始按钮文本
      selection: [], // 用于存储用户选择的项目
      dialogVisible: false,
      errorMessages: [],
      advancedSearchForm: {
        year: '',
        yangdibh: '',
        xzqhmc: '',
        lon: '',
        lat: '',
        hb: '',
        shengtaixitonglx: '',
      },
      advancedSearchVisible: false, // 控制高级搜索对话框显示
      tableData2: {
        plots: [],
        herbs: [],
        shrubs: [],
        trees: [],
      },
      pagination: {
        ydcurrentPage: 1,
        ydpageSize: 10,
        ydtotal: 0,
        cbcurrentPage: 1,
        cbpageSize: 10,
        cbtotal: 0,
        gmcurrentPage: 1,
        gmpageSize: 10,
        gmtotal: 0,
        qmcurrentPage: 1,
        qmpageSize: 10,
        qmtotal: 0,
        jycurrentPage: 1,
        jypageSize: 10,
        jytotal: 0,
      },
      excelurl: window.location.origin + window.location.pathname + '/样地数据.xlsx',
      information: [],
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    },
    // 添加计算属性用于检查 formDataExcel 是否为空
    isFormDataEmpty() {
      return this.formDataExcel.length === 0;
    },
    ydpaginatedData() {
      // 前端分页时使用
      const start = (this.pagination.ydcurrentPage - 1) * this.pagination.ydpageSize;
      return this.tableData2.plots.slice(start, start + this.pagination.ydpageSize);
    },
    cbpaginatedData() {
      // 前端分页时使用
      const start = (this.pagination.cbcurrentPage - 1) * this.pagination.cbpageSize;
      return this.tableData2.herbs.slice(start, start + this.pagination.cbpageSize);
    },
    gmpaginatedData() {
      // 前端分页时使用
      const start = (this.pagination.gmcurrentPage - 1) * this.pagination.gmpageSize;
      return this.tableData2.shrubs.slice(start, start + this.pagination.gmpageSize);
    },
    qmpaginatedData() {
      // 前端分页时使用
      const start = (this.pagination.qmcurrentPage - 1) * this.pagination.qmpageSize;
      return this.tableData2.trees.slice(start, start + this.pagination.qmpageSize);
    },
    jypaginatedData() {
      // 前端分页时使用
      const start = (this.pagination.jycurrentPage - 1) * this.pagination.jypageSize;
      return this.information.slice(start, start + this.pagination.jypageSize);
    }
  },
  watch: {
    selectedCategory(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.filterDataByCategory(newVal);
      }
    },
  },
  created() {
    const height = window.innerHeight - 200;
    this.tableheight = height;
    this.fetchData(this.queryForm);
    // this.getData();
  },
  mounted() { },
  methods: {
    filterDataByCategory(category) {
      if (category === "全部") {
        this.filteredData = this.tableData;
      } else {
        this.filteredData = this.tableData.filter(
          (item) => item.category === category
        );
      }
      this.paginatedData = this.filteredData;
      this.totalItems = this.filteredData.length;
      this.paginateData();
    },
    handleDialogClose(done) {
      // 清空相关数据
      this.selectedFile = null;
      this.errorMessages = [];
      this.formDataExcel = [];

      // 调用 done() 完成关闭
      done();
    },
    openDialog() {
      this.dialogVisible = true;
    },
    handleSelectionChange(val) {
      this.selection = val;
    },
    batchDelete() {
      if (this.selection.length === 0) {
        // 如果没有选中项目，不执行删除操作
        return;
      }

      MessageBox.confirm("确定要批量删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确定按钮
          const selectedIds = this.selection.map((item) => item.id);
          const idsString = selectedIds.join(",");
          console.log("idsString", idsString);
          this.$api
            .delData(idsString)
            .then((response) => {
              // 处理接口返回的数据或其他逻辑
              // 处理删除成功的情况
              console.log("批量删除成功", response.data);

              // 在前端移除已删除的项
              this.tableData = this.tableData.filter(
                (item) => !selectedIds.includes(item.id)
              );
              this.totalItems -= selectedIds.length; // 减少总项目数
              this.paginateData(); // 更新分页后的数据
              this.selection = []; // 清空用户选择的项目

              // 添加成功提示
              Message({
                message: "批量删除成功",
                type: "success",
                duration: 3000,
              });

              // 重新获取数据
              this.fetchData(this.queryForm);
            })
            .catch((error) => {
              // 处理失败的情况
              console.error("批量删除失败:", error);
              // 添加失败提示
              Message({
                message: "批量删除失败",
                type: "error",
                duration: 3000,
              });
            });
        })
        .catch(() => {
          // 用户点击了取消按钮
          console.log("用户点击了取消按钮");
        });
    },
    buildUrl(params) {
      const queryParams = new URLSearchParams(params).toString();
      return `${queryParams}`;
    },
    fetchData(obj) {
      console.log(obj)
      // 调用 user.js 中的 getData 方法
      let params = {
        laiyuan: '内大草普',
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      }
      const mergeWithFixed = (dynamicObj) =>
        Object.fromEntries(
          Object.entries({ ...params, ...dynamicObj })
            .filter(([_, v]) => v != null && v !== '')
        );
      const result = mergeWithFixed(obj);
      this.$api
        .getNdData(this.buildUrl(result))
        .then((response) => {
          if (response.data.code === 906) {
            // return  alert('token已过期')
            this.$router.push(`/login`);
          }

          console.log(222);
          console.log("数据", response);
          let data = response.data.data;
          this.paginatedData = data.list;
          this.totalItems = data.total;
          // this.tableData = response.data.data;
          // this.filterDataByCategory(this.selectedCategory);
          // this.totalItems = this.tableData.length;
          // this.paginateData();
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },

    // 普通搜索
    onSearch() {
      this.$nextTick(() => {
        this.fetchData(this.queryForm);
      });
    },

    // 修改
    handleButtonClick(row) {
      // 处理按钮点击事件
      // 可以根据需要执行特定操作
      console.log("点击了操作按钮，当前行数据:", row);
      // 获取当前行的 ID
      // const id = row.sampleinfoid;
      const id = row.id;
      // const id = row.sampleid;
      console.log(1111, id);
      // 导航到编辑页面
      this.$router.push({ name: "EditPage", params: { id } });
    },

    // 添加
    showForm() {
      console.log("添加");

      // 跳转到编辑页面
      this.$router.push({ name: "EditPage" });
    },

    // 删除

    async deleteItem(id) {
      console.log("删除id", id);
      try {
        MessageBox.confirm("确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$api
              .deletePlotsByid(id)
              .then((response) => {
                this.fetchData(this.queryForm);

                // 添加成功提示
                Message({
                  message: "删除成功",
                  type: "success",
                  duration: 3000,
                });
                this.fetchData(this.queryForm);
              })
              .catch((error) => {
                // 处理失败的情况
                console.error("失败:", error);
                // 添加失败提示
                Message({
                  message: "删除失败",
                  type: "error",
                  duration: 3000,
                });
              });
          })
          .catch(() => {
            // 用户点击了取消按钮
            console.log("用户点击了取消按钮");
          });
      } catch (error) {
        // 处理删除失败的情况
        console.error("删除失败", error);
      }
    },
    // 切换分页
    paginateData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      // this.paginatedData = this.tableData.slice(start, end);
      this.paginatedData = this.filteredData.slice(start, end);
    },

    handleCurrentChange(val) {
      // 当用户切换分页时触发
      this.currentPage = val;
      // this.paginateData();
      this.$nextTick(() => {
        this.fetchData(this.queryForm);
      })
    },
    openExcel() {
      this.$refs.exceluploadinput.click();
    },
    // 录入全部数据
    handleFileUpload(event) {
      // const loading = this.$loading({
      //   lock: true,
      //   text: '正在加载...',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.5)'
      // });
      this.information = [];
      this.tableData2 = {
        plots: [],
        herbs: [],
        shrubs: [],
        trees: [],
      }
      this.duplicateSampleIds.clear();
      this.errorMessages = []; // 清空之前的错误信息
      // 获取上传的Excel文件
      const file = event.target.files[0];
      console.log(file)
      // let data = readExcel()
      // console.log(data)
      // 清除输入值以确保即使选择相同的文件，onload 事件仍然会触发
      event.target.value = null;
      // 使用xlsx读取Excel文件
      const reader = new FileReader();

      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        console.log('1231312', workbook)
        let obj = readExcel(workbook);
        console.log(obj)
        this.tableData2.plots = obj.plots;
        this.pagination.ydtotal = obj.plots.length;
        this.tableData2.herbs = obj.herbs;
        this.pagination.cbtotal = obj.herbs.length;
        this.tableData2.shrubs = obj.shrubs;
        this.pagination.gmtotal = obj.shrubs.length;
        this.tableData2.trees = obj.trees;
        this.pagination.qmtotal = obj.trees.length;
        return
      };

      reader.readAsArrayBuffer(file);
    },

    handleSizeChange(val, name) {
      this.pagination[name + 'pageSize'] = val;
    },
    handleCurrentChange2(val, name) {
      this.pagination[name + 'currentPage'] = val;
    },

    getEnglishTableName(chineseTableName) {
      // 根据中文表名返回相对应的英文单词
      // 这里只是一个示例，你可能需要定义一个更完整的映射关系
      const tableMapping = {
        样地: "sampleInfo",
        草本: "herbYfList",
        灌木: "shrubYfList",
        乔木: "arborYfList",
        土壤: "soilCd",
        // 添加其他表格的映射关系
      };

      return tableMapping[chineseTableName] || chineseTableName;
    },
    insertAllDataFromExcel() {
      if (this.errorMessages.length > 0) {
        // 显示错误信息
        Message({
          message: this.errorMessages.join("; "),
          type: "error",
          duration: 5000,
        });
        return;
      }
      // 在点击录入数据按钮时，检查 formDataExcel 是否为空
      if (this.isFormDataEmpty) {
        // 如果为空，不执行后续逻辑
        Message({
          message: "请先选择Excel文件",
          type: "warning",
          duration: 3000,
        });
        return;
      }

      this.isButtonDisabled = true;
      this.buttonText = "录入中...";
      console.log("录入全部数据:", this.formDataExcel[0]);

      // 在这里可以执行表单录入的逻辑，使用 this.formData 中的数据
      this.$api
        .luruData(this.formDataExcel[0])
        .then((response) => {
          console.log("response", response);
          if (response.data.code === 0) {
            Message({
              message: "录入成功",
              type: "success",
              duration: 3000, // 持续时间，单位毫秒
            });
            this.formDataExcel = [];
            this.errorMessages = []; // 清空错误信息
            this.dialogVisible = false; // 关闭对话框
            // 录入成功后重新获取数据
            this.fetchData(this.queryForm);
          } else {
            Message({
              message: response.data.message || "录入失败",
              type: "error",
              duration: 3000,
            });
          }
        })
        .catch((error) => {
          console.log(error);
          Message({
            message: "录入失败，请检查数据格式",
            type: "error",
            duration: 3000,
          });
        })
        .finally(() => {
          // 数据录入完成后恢复按钮状态和文本
          this.isButtonDisabled = false;
          this.buttonText = "录入全部数据";
        });
    },
    // 显示高级搜索对话框
    showAdvancedSearch() {
      this.advancedSearchVisible = true;
    },

    // 处理高级搜索对话框关闭
    handleAdvancedSearchClose(done) {
      this.advancedSearchForm.keyword = "";
      this.advancedSearchForm.longitude = "";
      this.advancedSearchForm.latitude = "";
      done();
    },

    // 高级搜索
    handleAdvancedSearch() {
      this.fetchData(this.advancedSearchForm)
    },
    downloadTemplate() {
      // 使用完整的URL路径
      const baseUrl = window.location.origin;
      const link = document.createElement("a");
      link.href = `${baseUrl}/sample-template.xlsx`;
      link.download = "样地信息录入模板.xlsx";
      link.style.display = "none";

      // 添加到页面并触发下载
      document.body.appendChild(link);
      link.click();

      // 清理DOM
      document.body.removeChild(link);

      // 显示成功提示
      Message({
        message: "模板下载成功",
        type: "success",
        duration: 3000,
      });
    },
    format(timestamp) {
      const date = new Date(timestamp);
      const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      return formattedDate;
    },
    parseCustomDate(dateStr) {
      // 处理2021.7格式（缺少日）
      if (/^\d{4}\.\d{1,2}$/.test(dateStr)) {
        console.log('1111', dateStr)
        const [year, month] = dateStr.toString().split('.')
        return new Date(year, month - 1, 1) // 月份0-11

        // 处理2021.8.8格式
      } else if (/^\d{4}\.\d{1,2}\.\d{1,2}$/.test(dateStr)) {
        console.log('22222', dateStr)
        const [year, month, day] = dateStr.toString().split('.')
        return new Date(year, month - 1, day)

        // 处理20210523格式
      } else if (/^\d{8}$/.test(dateStr)) {
        console.log('33333', dateStr)
        const year = dateStr.toString().slice(0, 4)
        const month = dateStr.toString().slice(4, 6)
        const day = dateStr.toString().slice(6, 8)
        return new Date(`${year}-${month}-${day}`)

      } else {
        return;
      }
    },
    dataVerification() {
      let array = [];
      let array2 = [];
      let array3 = [];
      let array4 = [];
      this.tableData2.plots.forEach(element => {
        let date = this.parseCustomDate(element.surveyDate);
        if (!date) {
          array.push(`样地编号为${element.originalPlotId}的调查日期格式错误`);
        }
      });
      const pattern = /^\d+[\*xX×]\d+$/;
      this.tableData2.herbs.forEach(element => {
        if (!pattern.test(element.quadratAreaM2)) {
          array.push(`样地编号为${element.originalPlotId}草本样方编号为${element.herbQuadratId}的样方面积错误`);
        }
      });
      this.tableData2.shrubs.forEach(element => {
        if (!pattern.test(element.quadratArea)) {
          array.push(`样地编号为${element.originalPlotId}灌木样方编号为${element.shrubQuadratId}的样方面积错误`);
        }
      });
      this.tableData2.trees.forEach(element => {
        if (!pattern.test(element.quadratArea)) {
          array.push(`样地编号为${element.originalPlotId}乔木样方编号为${element.herbQuadratId}的样方面积错误`);
        }
      });
      this.information = array;
      this.pagination.jytotal = array.length;
    },
    handsubmit() {
      // if (this.information.length > 0) {
      //   Message({
      //     message: "错误数据请更改！",
      //     type: "warning",
      //     duration: 3000,
      //   });
      //   return
      // }
      this.$api.batAddPlot(this.tableData2).then((res) => {
        console.log(res);
        if (res.data.code == 0) {
          Message({
            message: res.data.data,
            type: "success",
          });
          this.fetchData(this.queryForm);
        } else {
          Message({
            message: res.data.data,
            type: "error",
          });
        }
      })
      this.dialogVisible = false;
    }
  },
};
</script>
<style scoped>
.el-main {
  color: #333;
  box-sizing: border-box;
}

.top {
  background-color: rgb(232, 232, 232);
  border-radius: 2px;
  padding-left: 20px;
  padding-top: 8px;
  padding-bottom: 7px;
  overflow: hidden;
}

.center {
  /* height: 400px; */
}

.demo-form-inline .el-form-item {
  margin-bottom: 2px;
  vertical-align: top;
  margin-right: 16px;
}

.bottom {
  text-align: right;
}

.file-upload {
  margin-right: 20px;
  /* 调整按钮之间的间距 */
}

.file-upload input {
  display: none;
}

/* 添加样式来美化文件选择按钮 */
.file-upload {
  display: inline-block;
  cursor: pointer;
  padding: 10px 20px;
  background-color: #3498db;
  color: #fff;
  border-radius: 5px;
}

.dialog-content {
  display: flex;
  /* flex-direction: column; */
  /* align-items: center; */
  justify-content: center;
  height: 100%;
}

.batch-btn-row {
  display: flex;
  gap: 16px;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.batch-btn {
  margin: 0 !important;
  min-width: 90px;
}

.file-upload.batch-btn {
  padding: 7px 18px;
  font-size: 14px;
  background-color: #409eff;
  color: #fff;
  border-radius: 4px;
  border: none;
  transition: background 0.2s;
}

.file-upload.batch-btn:hover {
  background-color: #66b1ff;
}
</style>

<style>
.el-dialog__header {
  border-bottom: 1px solid #DCDFE6;
}

.excel-dialo .el-dialog__body {
  padding: 10px 20px;
}

.excel-dialo .el-dialog__footer {
  border-top: 1px solid #DCDFE6;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
</style>
